<?php

/**
 * UploadController - Controller dùng để upload image
 * 
 * @author huytbt
 * @date 2011-07-11
 * @version 1.0
 */
class ManageUploadController extends Controller
{
	public $backend_left_menu = "application.modules.products.views.admin_menu._left_menu";
	public $backend_left_menu_datas = array('list'	=>	array());
	//public $backend_left_menu_datas = false;
	private $_model;
	public $layout='//layouts/main';
	
	public function init()
	{
			Yii::app()->theme = 'backend';
			parent::init();
	}

	/**
	 * actionIndex - Action dùng để render ra form upload
	 */
	public function actionIndex($product_id)
	{
		$baseScriptUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . '/../assets/products');
		Yii::app()->getClientScript()->registerCssFile($baseScriptUrl.'/css/products.css');

		$model = new ProductImage;

		$this->render('index', array(
				'model' => $model,
		));
	}
	
	/**
	 * actionUpload - Action dùng để upload image
	 */
	public function actionUpload()
	{
		if (isset($_POST['ProductImage'])) {
			$model = new ProductImage;
			$model->attributes = $_POST['ProductImage'];
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
				$model->image = $fileUpload->name;
				$model->name = $fileUpload->name;
				
				if ($model->validate()) {
					// Thiết lập đường dẫn upload
					$uploadPath = YiiBase::getPathOfAlias('webroot'). Yii::app()->controller->module->product_image['url'];
					//$uploadPath = YiiBase::getPathOfAlias('webroot') . '/wwwroot/upload_files/news/'; 
					if (!is_dir($uploadPath)) {
						@mkdir($uploadPath);
						@chmod($uploadPath, 0777);
					}
					
					// Thiết lập các thông tin để lưu vào DB
					//$model->upload_time = date('Y-m-d H:i:s', time());
					
					// Upload image
					$filename = time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$filename = trim($filename);
					$fileUpload->saveAs($uploadPath.$filename);

					Yii::import('ext.phpthumb.EasyPhpThumb');
					$resize = new EasyPhpThumb();
					$resize->init();
					$resize->setThumbsDirectory($uploadPath);
					$resize->load($uploadPath.$filename)
						->resize($this->module->product_image['lager']['width'], $this->module->product_image['lager']['height'])
						->save($filename);
					
					
					
					// Create thumb
					$thumbsPath = $uploadPath.'/thumbs';
					if (!is_dir($thumbsPath)) {
						@mkdir($thumbsPath);
						@chmod($thumbsPath, 0777);
					}
					
					$thumbs = new EasyPhpThumb();
					$thumbs->init();
					$thumbs->setThumbsDirectory($thumbsPath);
					$thumbs->load($uploadPath.$filename)
							->resize($this->module->image['thumbnail']['width'], $this->module->image['thumbnail']['height'])
							->save($filename);
					
					
					
					
					
					// Save info to dâtbase
					$model->image = $filename;
					$model->save();
					
					// Print result
					echo CJSON::encode(array(
						array(
							'name' => $model->name,
							'content_type' => $fileUpload->type,
							'size' => $fileUpload->size,
							'url' => Yii::app()->createUrl('/').Yii::app()->controller->module->product_image['url'].$filename,
							'thumbnail_url' => Yii::app()->createUrl('/') . Yii::app()->controller->module->product_image['url'] . 'thumbs/' . $filename,
							'delete_url' => Yii::app()->createUrl('/products/manageUpload/delete', array('id'=>$model->id)),
							'delete_type' => 'DELETE',
						)
					));
				} else {
					// Print errors
					$strError = '';
					foreach ($model->getErrors() as $error)
					{
						foreach ($error as $text)
							$strError .= $text . ' ';
					}
					echo CJSON::encode(array(array('name'=>$fileUpload->name,'error'=>$strError)));
				}
			}
			Yii::app()->end();
		}
	}
	
	/**
	 * actionDelete - Action dùng để xóa image đã upload
	 *
	 * @param string $id 
	 */
	public function actionDelete($id)
	{
			$image = ProductImage::model()->findByPk($id);
			$uploadPath = Yii::app()->createUrl('/').'/wwwroot/upload_files/product_images/';
			$filename = $uploadPath . $image->image;
			if (is_file($filename)) @unlink($filename);
			$filenameThumb = $uploadPath . '/thumbs/' . $image->image;
			if (is_file($filenameThumb)) @unlink($filenameThumb);
			$image->delete();
	}

}